package xyz.hubery.event;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.MimeTypeUtils;
import xyz.hubery.constant.Constants;
import xyz.hubery.enums.KlineType;
import xyz.hubery.model.MessagePayload;
import xyz.hubery.stream.Source;


/**
 * K 线推送事件
 */
@Slf4j
public class KlineEvent implements Runnable, Event {
    /**
     * 交易对标识符
     */
    private String symbol;

    /**
     * 通道
     */
    private static final String CHANNEL = "market.%s.kline.%s";

    /**
     * redis key 前缀
     */
    private static final String KEY_PREFIX = Constants.REDIS_KEY_TRADE_KLINE;


    private RedisTemplate<String, Object> redisTemplate;

    private Source source;

    public KlineEvent() {
    }

    public KlineEvent(String symbol, RedisTemplate<String, Object> redisTemplate, Source source) {
        this.symbol = symbol;
        this.redisTemplate = redisTemplate;
        this.source = source;
    }

    /**
     * 事件触发处理机制
     */
    @Override
    public void handle() {
        // 遍历所有的k线类型
//        for (KlineType klineType : KlineType.values()) {  // 卡死机了
        MessagePayload payload = new MessagePayload();
        // 设置通道
        payload.setChannel(String.format(CHANNEL, symbol.toLowerCase(), "1min"));
        // 从redis中获取内容
        String redisKey = new StringBuilder(KEY_PREFIX).append(symbol.toLowerCase()).append(":").append("1min").toString();
        Object data = redisTemplate.opsForList().index(redisKey, 0);
        if (data != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tick", data);
            payload.setBody(jsonObject.toJSONString());

            String s = jsonObject.toString();
            log.warn("KlineEvent 消息内容大小：{}", s.getBytes().length);

            // 发送数据
            source.subscribeEventOutput()
                    .send(
                            MessageBuilder
                                    .withPayload(payload)
                                    .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
                                    .build()
                    );
        }
//        }
    }

    /**
     * 让线程池调度
     */
    @Override
    public void run() {
        handle();
    }


}